package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.annotaion.ApiMethod;
import com.xmy.cultivate.entity.AuthAdminContent;
import com.xmy.cultivate.entity.Quarter;
import com.xmy.cultivate.entity.SchoolQuarter;
import com.xmy.cultivate.entity.response.ArrivalRate;
import com.xmy.cultivate.entity.response.LackRecourseRate;
import com.xmy.cultivate.entity.response.MathChaPlan;
import com.xmy.cultivate.entity.views.FenAdminData;
import com.xmy.cultivate.entity.views.LeadDataRs;
import com.xmy.cultivate.entity.views.RenewClassRecord;
import com.xmy.cultivate.entity.views.StudentRatePay;
import com.xmy.cultivate.service.IAuthAdminContentService;
import com.xmy.cultivate.service.ILackCourseLogService;
import com.xmy.cultivate.service.IQuarterService;
import com.xmy.cultivate.service.ISchoolQuarterService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 缺课记录 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2023-07-28
 */
@RestController
@RequestMapping("/api/lackCourseLog")
public class LackCourseLogController extends BaseController {

    @Autowired
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    ISchoolQuarterService iSchoolQuarterService;

    @Autowired
    IAuthAdminContentService iAuthAdminContentService;

    @GetMapping("/getLackRade")
    public Result getLackRade(@RequestParam(value = "yearPart", required = true) Integer yearPart,
                              @RequestParam(value = "quarterNum", required = true) Integer quarterNum,
                              @RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                              @RequestParam(value = "subjectsId", required = false) Long subjectsId,
                              @RequestParam(value = "trackId", required = false) Long trackId,
                              @RequestParam(value = "type", required = true) Integer type,
                              @RequestParam(value = "startDate", required = false) String startDate,
                              @RequestParam(value = "endDate", required = false) String endDate,
                              @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType) {

        Quarter quarter = iQuarterService.getNowQuarter();
        List<LackRecourseRate> lackRecourseRateList = iLackCourseLogService.getLackRade(schoolId, subjectsId, type, yearPart, quarterNum, startDate, endDate, trackId, lessonType);
        return new Result(Code.OK, new PageResult(lackRecourseRateList, (long) lackRecourseRateList.size(), 1L));
    }

    /**
     * @param yearPart
     * @param quarterNum
     * @param schoolId
     * @param teacherId
     * @param subjectsId
     * @param gradeId
     * @param trackId
     * @param type
     * @param detailType
     * @param startDate
     * @param endDate
     * @param pageNum
     * @param pageSize
     * @param lessonType
     * @param stuType    1为老生，2为新生
     * @param isLack
     * @return
     */
    @GetMapping("/getLackRadeDetail")
    public Result getLackRadeDetail(@RequestParam(value = "yearPart", required = true) Integer yearPart,
                                    @RequestParam(value = "quarterNum", required = true) Integer quarterNum,
                                    @RequestParam(value = "schoolId", required = false) Long schoolId,
                                    @RequestParam(value = "teacherId", required = false) Long teacherId,
                                    @RequestParam(value = "subjectsId", required = false) Long subjectsId,
                                    @RequestParam(value = "gradeId", required = false) Long gradeId,
                                    @RequestParam(value = "trackId", required = false) Long trackId,
                                    @RequestParam(value = "type", required = true) Integer type,
                                    @RequestParam(value = "detailType", required = false, defaultValue = "1") Integer detailType,
                                    @RequestParam(value = "startDate", required = false) String startDate,
                                    @RequestParam(value = "endDate", required = false) String endDate,
                                    @RequestParam(value = "pageNum", required = false) Long pageNum,
                                    @RequestParam(value = "pageSize", required = false) Long pageSize,
                                    @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
                                    @RequestParam(value = "stuType", required = false, defaultValue = "1") String stuType,
                                    @RequestParam(value = "isLack", required = false, defaultValue = "1") String isLack) {

        IPage<LackRecourseRate> iPage = new Page<>(pageNum, pageSize);

        Quarter quarter = iQuarterService.getNowQuarter();

        iLackCourseLogService.getLackRadeDetail(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, type, startDate, endDate, trackId, detailType, lessonType, isLack, stuType);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), (long) iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 缺课补课
     */
    @ApiMethod(value = "home:edu:new-students-absence-course", description = "缺课补课率")
    @GetMapping("/getRepairLackRade")
    public Result getRepairLackRade(@RequestParam(value = "yearPart", required = true) Integer yearPart,
                                    @RequestParam(value = "quarterNum", required = true) Integer quarterNum,
                                    @RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                    @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                    @RequestParam(value = "trackId", required = false) Long trackId,
                                    @RequestParam(value = "type", required = true) Integer type,
                                    @RequestParam(value = "startLessonNum", required = false) String startLessonNum,
                                    @RequestParam(value = "endLessonNum", required = false) String endLessonNum,
                                    @RequestParam(value = "startDate", required = false) String startDate,
                                    @RequestParam(value = "endDate", required = false) String endDate,
                                    @RequestParam(value = "teamId", required = false) String teamId,
                                    @RequestParam(value = "classify", required = false) String classify,
                                    @RequestParam(value = "trackType", required = false) String trackType,
                                    @RequestParam(value = "lackType", required = false, defaultValue = "0") String lackType,// 缺课分类
                                    @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
                                    @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeIdStr,
                                    @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType) {
        List<LackRecourseRate> lackRecourseRateList = new ArrayList<>();

        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, this.adminId, this.baseSchoolIdStr);
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();
        if (authAdminContent.getIsPerson() == 1) {
            if (!type.equals(1) && !type.equals(2)) {
                return new Result(Code.OK, new PageResult<>(new ArrayList<>(), (long) 0, 1L));
            }
        }

        if (StringUtils.isBlank(yearClassId)) {
            yearClassId = authAdminContent.getYearClassIds();
        } else {
            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearClassId);
            leadDataRs.setYearClassIds(leadYearClassId);

            yearClassId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearClassId);
        }

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }


        if (type != 5) {
            lackRecourseRateList = iLackCourseLogService.getRepairLackRade(schoolId, subjectsId, type, yearPart, quarterNum, startDate, endDate, trackId, lessonType, yearClassId, classTypeIdStr, startLessonNum, endLessonNum, lackType, authAdminContent, leadDataRs);

            if (type == 6) {
                List<LackRecourseRate> collectList = new ArrayList<>();

                QueryWrapper queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("year_part", yearPart);
                queryWrapper.eq("quarter_num", quarterNum);
                queryWrapper.eq("pid", 0);
                List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

                for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                    LackRecourseRate lackRecourseRate = new LackRecourseRate();
                    lackRecourseRate.setSchoolId(schoolQuarter.getSchoolId());
                    lackRecourseRate.setSchoolName(schoolQuarter.getSchoolName());
                    lackRecourseRate.setSchoolPid(schoolQuarter.getPid());
                    lackRecourseRate.setStudentAllCount(0);
                    lackRecourseRate.setLackCourseCount(0);
                    lackRecourseRate.setAllRepairCount(0);
                    lackRecourseRate.setRepairCount(0);

                    collectList.add(lackRecourseRate);
                }

                for (LackRecourseRate lackRecourseRate : collectList) {
                    List<LackRecourseRate> childRates = new ArrayList<>();
                    for (LackRecourseRate arrivalRateChild : lackRecourseRateList) {
                        if (lackRecourseRate.getSchoolId().equals(arrivalRateChild.getSchoolId()) || lackRecourseRate.getSchoolId().equals(arrivalRateChild.getSchoolPid())) {
                            childRates.add(arrivalRateChild);
                            if (lackRecourseRate.getStudentAllCount() != null) {
                                lackRecourseRate.setStudentAllCount(arrivalRateChild.getStudentAllCount() + lackRecourseRate.getStudentAllCount());
                            }
                            if (lackRecourseRate.getLackCourseCount() != null) {
                                lackRecourseRate.setLackCourseCount(arrivalRateChild.getLackCourseCount() + lackRecourseRate.getLackCourseCount());
                            }
                            if (lackRecourseRate.getAllRepairCount() != null) {
                                lackRecourseRate.setAllRepairCount(arrivalRateChild.getAllRepairCount() + lackRecourseRate.getAllRepairCount());
                            }
                            if (lackRecourseRate.getRepairCount() != null) {
                                lackRecourseRate.setRepairCount(arrivalRateChild.getRepairCount() + lackRecourseRate.getRepairCount());
                            }
                        }
                    }
                    lackRecourseRate.setChildRateList(childRates);
                }

                lackRecourseRateList = collectList;
            }

        } else if (type == 5) {
            lackRecourseRateList = iLackCourseLogService.getRepairLackRadeTeamList(yearPart, quarterNum, subjectsId, startDate, endDate, yearClassId, classTypeIdStr, teamId, classify, trackType, startLessonNum, endLessonNum, lackType, authAdminContent, schoolId, leadDataRs);
        }

        return new Result(Code.OK, new PageResult<>(lackRecourseRateList, (long) lackRecourseRateList.size(), 1L));
    }

    /**
     * 缺课补课详情
     */
    @ApiMethod(value = "home:edu:new-students-absence-course", description = "缺课补课率")
    @GetMapping("/getRepairLackRadeDetailRepair")
    public Result getRepairLackRadeDetail(@RequestParam(value = "yearPart", required = true) Integer yearPart,
                                          @RequestParam(value = "quarterNum", required = true) Integer quarterNum,
                                          @RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                          @RequestParam(value = "teacherId", required = false) Long teacherId,
                                          @RequestParam(value = "gradeId", required = false) Long gradeId,
                                          @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                          @RequestParam(value = "trackId", required = false) Long trackId,
                                          @RequestParam(value = "type", required = true) Integer type,
                                          @RequestParam(value = "isCollect", required = false, defaultValue = "0") Integer isCollect,
                                          @RequestParam(value = "lessonNum", required = false) String lessonNum,
                                          @RequestParam(value = "startDate", required = false) String startDate,
                                          @RequestParam(value = "endDate", required = false) String endDate,
                                          @RequestParam(value = "teamId", required = false) String teamId,
                                          @RequestParam(value = "classify", required = false) String classify,
                                          @RequestParam(value = "trackType", required = false) String trackType,
                                          @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
                                          @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeIdStr,
                                          @RequestParam(value = "pageNum", required = false, defaultValue = "-1") Long pageNum,
                                          @RequestParam(value = "pageSize", required = false, defaultValue = "-1") Long pageSize,
                                          @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType,
                                          @RequestParam(value = "lackType", required = false, defaultValue = "0") String lackType,// 缺课分类
                                          @RequestParam(value = "startLessonNum", required = false, defaultValue = "") String startLessonNum,
                                          @RequestParam(value = "endLessonNum", required = false, defaultValue = "") String endLessonNum,
                                          @RequestParam(value = "isRepair", required = false, defaultValue = "") String isRepair) {
        IPage<LackRecourseRate> iPage = new Page<>(pageNum, pageSize);

        // 获取权限
        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, this.adminId, this.baseSchoolIdStr);
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();
        if (authAdminContent.getIsPerson() == 1) {
            if (!type.equals(1) && !type.equals(2)) {
                return new Result(Code.OK, new PageResult<>(new ArrayList<>(), (long) 0, 1L));
            }
        }
        if (teacherId != null) {
            if (!teacherId.equals(leadDataRs.getTeacherId())) {
                leadDataRs.setTeacherId(0L);
            }
        }

        if (StringUtils.isBlank(yearClassId)) {
            yearClassId = authAdminContent.getYearClassIds();
        } else {
            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearClassId);
            leadDataRs.setYearClassIds(leadYearClassId);

            yearClassId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearClassId);
        }

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }


        if (type != 5) {
            iLackCourseLogService.getRepairLackRadeDetail(iPage, schoolId, teacherId, gradeId, subjectsId, type, yearPart, quarterNum, startDate, endDate, trackId, lessonType, yearClassId, isRepair, classTypeIdStr, isCollect, lessonNum, startLessonNum, endLessonNum, lackType, authAdminContent, leadDataRs);
        } else if (type == 5) {
            iLackCourseLogService.getRepairLackRadeTeamDetail(iPage, yearPart, quarterNum, schoolId, teacherId, gradeId, subjectsId, startDate, endDate, yearClassId, isRepair, classTypeIdStr, teamId, classify, trackType, isCollect, lessonNum, startLessonNum, endLessonNum, lackType, authAdminContent, leadDataRs);
        }

        return new Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    /**
     * 缺课补课
     */
    @GetMapping("/getRepairLackRadeIFeign")
    public List<LackRecourseRate> getRepairLackRadeIFeign(@RequestParam(value = "yearPart", required = true) Integer yearPart,
                                                          @RequestParam(value = "quarterNum", required = true) Integer quarterNum,
                                                          @RequestParam(value = "schoolId", required = false, defaultValue = "") String schoolId,
                                                          @RequestParam(value = "subjectsId", required = false) String subjectsId,
                                                          @RequestParam(value = "trackId", required = false) Long trackId,
                                                          @RequestParam(value = "type", required = true) Integer type,
                                                          @RequestParam(value = "startLessonNum", required = false) String startLessonNum,
                                                          @RequestParam(value = "endLessonNum", required = false) String endLessonNum,
                                                          @RequestParam(value = "startDate", required = false) String startDate,
                                                          @RequestParam(value = "endDate", required = false) String endDate,
                                                          @RequestParam(value = "teamId", required = false) String teamId,
                                                          @RequestParam(value = "classify", required = false) String classify,
                                                          @RequestParam(value = "trackType", required = false) String trackType,
                                                          @RequestParam(value = "lackType", required = false, defaultValue = "0") String lackType,// 缺课分类
                                                          @RequestParam(value = "yearClassId", required = false, defaultValue = "") String yearClassId,
                                                          @RequestParam(value = "classTypeId", required = false, defaultValue = "") String classTypeIdStr,
                                                          @RequestParam(value = "lessonType", required = false, defaultValue = "1") String lessonType) {
        List<LackRecourseRate> lackRecourseRateList = new ArrayList<>();

        FenAdminData adminData = iAuthAdminContentService.getAdminData(yearPart, quarterNum);

        // 权限校区id
        String adminDataSchoolId = adminData.getBaseSchoolIdList().stream().map(Object::toString).collect(Collectors.joining(","));

        AuthAdminContent authAdminContent = iAuthAdminContentService.getPermissionForTeacherId(yearPart, quarterNum, adminData.getAdminId(), adminDataSchoolId);
        LeadDataRs leadDataRs = authAdminContent.getLeadDataRs();

        if (StringUtils.isBlank(yearClassId)) {
            yearClassId = authAdminContent.getYearClassIds();
        } else {
            String leadYearClassId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getYearClassIds(), yearClassId);
            leadDataRs.setYearClassIds(leadYearClassId);

            yearClassId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getYearClassIds(), yearClassId);
        }

        if (StringUtils.isBlank(subjectsId)) {
            subjectsId = authAdminContent.getSubjectsIds();
        } else {
            String leadSubjectsId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSubjectsIds(), subjectsId);
            leadDataRs.setSubjectsIds(leadSubjectsId);

            subjectsId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSubjectsIds(), subjectsId);
        }

        if (StringUtils.isBlank(schoolId)) {
            schoolId = authAdminContent.getSchoolIds();
        } else {
            String leadSchoolId = iAuthAdminContentService.getIntersectionForStr(leadDataRs.getSchoolIds(), schoolId);
            leadDataRs.setSchoolIds(leadSchoolId);

            schoolId = iAuthAdminContentService.getIntersectionForStr(authAdminContent.getSchoolIds(), schoolId);
        }

        if (type != 5) {
            lackRecourseRateList = iLackCourseLogService.getRepairLackRade(schoolId, subjectsId, type, yearPart, quarterNum, startDate, endDate, trackId, lessonType, yearClassId, classTypeIdStr, startLessonNum, endLessonNum, lackType, authAdminContent, leadDataRs);

            if (type == 6) {
                List<LackRecourseRate> collectList = new ArrayList<>();

                QueryWrapper queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("year_part", yearPart);
                queryWrapper.eq("quarter_num", quarterNum);
                queryWrapper.eq("pid", 0);
                List<SchoolQuarter> schoolQuarterList = iSchoolQuarterService.list(queryWrapper);

                for (SchoolQuarter schoolQuarter : schoolQuarterList) {
                    LackRecourseRate lackRecourseRate = new LackRecourseRate();
                    lackRecourseRate.setSchoolId(schoolQuarter.getSchoolId());
                    lackRecourseRate.setSchoolName(schoolQuarter.getSchoolName());
                    lackRecourseRate.setSchoolPid(schoolQuarter.getPid());
                    lackRecourseRate.setStudentAllCount(0);
                    lackRecourseRate.setLackCourseCount(0);
                    lackRecourseRate.setAllRepairCount(0);
                    lackRecourseRate.setRepairCount(0);

                    collectList.add(lackRecourseRate);
                }

                for (LackRecourseRate lackRecourseRate : collectList) {
                    List<LackRecourseRate> childRates = new ArrayList<>();
                    for (LackRecourseRate arrivalRateChild : lackRecourseRateList) {
                        if (lackRecourseRate.getSchoolId().equals(arrivalRateChild.getSchoolId()) || lackRecourseRate.getSchoolId().equals(arrivalRateChild.getSchoolPid())) {
                            childRates.add(arrivalRateChild);
                            if (lackRecourseRate.getStudentAllCount() != null) {
                                lackRecourseRate.setStudentAllCount(arrivalRateChild.getStudentAllCount() + lackRecourseRate.getStudentAllCount());
                            }
                            if (lackRecourseRate.getLackCourseCount() != null) {
                                lackRecourseRate.setLackCourseCount(arrivalRateChild.getLackCourseCount() + lackRecourseRate.getLackCourseCount());
                            }
                            if (lackRecourseRate.getAllRepairCount() != null) {
                                lackRecourseRate.setAllRepairCount(arrivalRateChild.getAllRepairCount() + lackRecourseRate.getAllRepairCount());
                            }
                            if (lackRecourseRate.getRepairCount() != null) {
                                lackRecourseRate.setRepairCount(arrivalRateChild.getRepairCount() + lackRecourseRate.getRepairCount());
                            }
                        }
                    }
                    lackRecourseRate.setChildRateList(childRates);
                }

                lackRecourseRateList = collectList;
            }

        } else if (type == 5) {
            lackRecourseRateList = iLackCourseLogService.getRepairLackRadeTeamList(yearPart, quarterNum, subjectsId, startDate, endDate, yearClassId, classTypeIdStr, teamId, classify, trackType, startLessonNum, endLessonNum, lackType, authAdminContent, schoolId, leadDataRs);
        }


        return lackRecourseRateList;
    }

}